<template>
  <div>
    <el-card>
      <CategorySelector  :isShowList="isShowList" @changeCategory="changeCategory"></CategorySelector>
    </el-card>
    <el-card style="margin-top: 20px">
      <!--    列表页面  -->
      <div v-show="isShowList">
        <!--      category3Id 一开始空串 转化成布尔值是false 取反 true 时 disabled生效 即不可用 当获取到数据时为true 取反 false 此时disabled不生效 即可用-->
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="showAddDiv">添加属性</el-button>
        <el-table
          border
          style="width: 100%"
          :data="attrList">
          <el-table-column

            type="index"
            prop="prop"
            align="center"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150">
          </el-table-column>
          <el-table-column
            prop="address"
            label="属性列表"
            width="width"
          >
            <template slot-scope="{row,$index}">
              <el-tag type="danger" v-for="(attrValue,index) in row.attrValueList" :key="attrValue.id">
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150"
          >
            <template slot-scope="{row,$index}">
              <HintButton type="warning" icon="el-icon-edit" size='mini' title="修改"
                          @click="showUpdateDiv(row)"></HintButton>
              <el-popconfirm
                @onComfirm="deleteAttr(row)"
                :title="`你确定要删除${row.attrName}吗`"
              >
                <HintButton slot="reference"  type="danger" icon="el-icon-delete" size='mini' title="删除"
                            style="margin-left: 10px"></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--添加或修改页面-->
      <div v-show="!isShowList">
        <el-form :inline="true" :model="attrForm">
          <el-form-item label="属性名">
            <el-input v-model="attrForm.attrName" placeholder="请输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <el-button :disabled="!attrForm.attrName" type="primary" icon="el-icon-plus" @click="addAttrValue">添加属性值</el-button>
        <el-button @click="isShowList=true">取消</el-button>
        <el-table
          border
          :data="attrForm.attrValueList"
          style="width: 100%;margin-bottom: 20px">
          <el-table-column
            prop="prop"
            type="index"
            align="center"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值姓名"
            width="width">
            <template slot-scope="{row,$index}">
              <el-input :ref="$index" size="mini" v-if="row.isEdit" @blur="toSpan(row)"
                        @keyup.enter.native="toSpan(row)" v-model="row.valueName" placeholder=""></el-input>
              <span v-else style="display: block ;width: 100px" @click="toInput(row,$index)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作">
            <template slot-scope="{row,$index}">
              <el-popconfirm
                :title="`你确定要删除${row.valueName}吗?`"
                @onConfirm="attrForm.attrValueList.splice($index,1)"
              >
                <HintButton slot="reference" type="danger" title="删除" size="mini" icon="el-icon-delete"></HintButton>
              </el-popconfirm>
            </template>


          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="attrForm.attrValueList.length===0">保存</el-button>
        <el-button @click="isShowList=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep.js";

export default {
  name: "AttrList",
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      attrForm: {//收集数据最终收集成什么样子是从接口文档中来的/admin/product/saveAttrInfo
        attrName: "",
        attrValueList: [
          /* {
             attrId: 0,
             id: 0,
             valueName: ""
           }*/
        ],
        categoryId: 0,
        categoryLevel: 3,
      },
      isShowList: true,
    }
  },
  methods: {
    //自定义事件
    changeCategory({categoryId, level}) {
      //父组件获取到1级id要清空自己的23级id属性列表数据
      if (level === 1) {
        this.category2Id = ''
        this.category3Id = ''
        this.attrList = []

        this.category1Id = categoryId
      } else if (level === 2) {
        //父组件获取到2级id要清空自己的3级id级属性列表数据
        this.category3Id = ''
        this.attrList = []

        this.category2Id = categoryId
      } else {
        //父组件获取到3级id要清空获取属性列表数据
        this.category3Id = ''
        this.attrList = []
        this.category3Id = categoryId
        this.getAttrList()
      }
    },
    //请求获取属性列表数据
    async getAttrList() {
      let {category1Id, category2Id, category3Id} = this
      try {
        const result = await this.$API.attr.getAttrList(category1Id, category2Id, category3Id)
        if (result.code === 200 || result.code === 20000) {
          /*console.log(result.data)//获得数据时需要选一级二级三级 然后再f12查看数据是否请求成功*/
          this.attrList = result.data

        }
      } catch (error) {
        this.$message.error('获取属性数据失败')
      }

    },
    //添加属性按钮显示添加属性页面
    showAddDiv() {
      this.isShowList = false
      this.attrForm = {
        attrName: "",
        attrValueList: [
          /* {
             attrId: 0,
             id: 0,
             valueName: ""
           }*/
        ],
        categoryId: this.category3Id,
        categoryLevel: 3,
      }
    },
    //点击修改按钮
    showUpdateDiv(row) {
      this.isShowList = false
      // 用到深拷贝
      //由于属性对象当中属性值列表也是对象数据，浅拷贝属性值列表数据还是同一个，所以浅拷贝搞不定对象内部的对象数据
      this.attrForm = cloneDeep(row)
      this.attrForm.attrValueList.forEach(item => {
        // item.isEdit = false
        // item.isEdit = false isEdit不是响应式的属性，因为一上来data内部没这个属性
        //这个属性是点击按钮才添加的，此时，数据监视早都结束了，isEdit不可能被监视到，添加的太晚了
        // 它就不是响应式，修改的时候，也不会影响到页面
        this.$set(item, 'isEdit', false)//这样添加新的属性才是响应式的
      })
    },
    //点击添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        //获取当前属性值所属属性的id 添加属性就没有是undefined 修改属性的时候就有
        valueName: '',
        isEdit: true
      })
      //让新添加的属性值自动获取焦点
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus()
      })
    },
    //点击Input框 失去焦点和键盘按下回车事件切换成span
    toSpan(row) {
      //input在切换为span之前要判断数据合法性
      //1、数据是不是空的 输入的内容不能有空的 如果有空的 清空 结束本函数
      if (row.valueName.trim() === '') {
        row.valueName = ''
        return
      }
      //2、除了自己以外，输入的数据是不是和其它的属性值名称重复
      let isRepeat = this.attrForm.attrValueList.some(item => {
        if (item !== row) {
          return row.valueName === item.valueName
        }
      })
      if (isRepeat) {
        this.$message.success('输入的值不能重复')
        row.valueName = ''
        return;
      }
      row.isEdit = false
    },
    //从span切换到input
    toInput(row, index) {
      row.isEdit = true
      this.$nextTick(() => {
        //让对应的这一项自动获取焦点
        this.$refs[index].focus()
      })
    },
    //点击保存按钮 发请求
    async save() {
      //请求需要的参数
      let attr = this.attrForm
      //整理参数 //把isEdit删除 这个只做前端判断的
      //1、属性值名称如果为空串，从属性值列表当中去除
      //2、属性值当中去除isEdit属性

      /*      attr.attrValueList = attr.attrValueList.filter(item => item.valueName !== '')
            attr.attrValueList.forEach(item => delete item.isEdit)*/
      //也可以这样写:
      attr.attrValueList = attr.attrValueList.filter(item => {
          if (item.valueName !== '') {
            delete item.isEdit
            return true
          }
        }
      )
      //3、属性值列表如果没有属性值，不发请求
      if (attr.attrValueList.length === 0) {
        /*this.$message.success('输入的属性值不能为空')*/
        return
      }
      //发请求
      try {
        const result = await this.$API.attr.addOrUpdate(attr)
        //请求成功干啥
        if (result.code === 20000 || result.code === 200) {
          this.$message.success('保存数据成功')
          //切换到列表页
          this.isShowList = true
          await this.getAttrList()//重新发请求获取数据
        }
      } catch (error) {
        this.$message.error('保存数据失败')
      }


      //请求失败干啥
    },
    //点击列表页的删除按钮 删除
     async deleteAttr(row){
      try {
        const  result= await this.$API.attr.delete(row.id)
        if (result.code===20000||result.code===200){
          this.$message.success('删除成功')
          await this.getAttrList()
        }
      }catch (error){
        this.$message.error('删除失败')
      }

    }
  }
}
</script>

<style scoped>

</style>
